package au.com.centrumsystems.hudson.plugin.buildpipeline;

import hudson.model.AbstractBuild;

import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;

import java.util.logging.Logger;
import javax.annotation.Nullable;

import au.com.centrumsystems.hudson.plugin.util.revision.Extractor;

public class RevisionHeader extends HeaderForm {
   
    public interface Factory {

        RevisionHeader create(AbstractBuild<?, ?> build);
    }

    private static final Logger LOGGER = Logger.getLogger(RevisionHeader.class.getName());

    private final AbstractBuild<?, ?> build;
    private final Extractor.Factory extractorFactory;

    @Inject
    public RevisionHeader(@Assisted AbstractBuild<?, ?> build, @Nullable Extractor.Factory extractorFactory) {
        // Preconditions.notNull
        this.build = build;
        this.extractorFactory = extractorFactory;
    }

    public String getRevision() {
        try {
            if (extractorFactory != null) {
                return extractorFactory.create(build.getProject()).extract(build);
            }
        } catch (Exception e) {
          LOGGER.warning(e.toString());
        } 
        return "No revision";
    }

    /**
     * Shortened revision (git SHA1 can get long
     * 
     * @return shortened revision
     */
    public String getShortRevision() {
        if (getRevision().length() > 22) {
            return getRevision().substring(0, 22) + "...";
        }
        return getRevision();
    }
}

